package com.army.common.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Slf4j
@Configuration
@AllArgsConstructor
@EnableBatchProcessing
public class SpringBatchConfig extends DefaultBatchConfigurer {
    private final DataSource dataSource;
    private final PlatformTransactionManager transactionManager;

    @NonNull
    @Override
    protected JobLauncher createJobLauncher() {
        SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
        try {
            JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
            jobRepositoryFactoryBean.setTransactionManager(transactionManager);
            jobRepositoryFactoryBean.setDataSource(dataSource);
            jobRepositoryFactoryBean.setIsolationLevelForCreate("ISOLATION_READ_COMMITTED");
            jobRepositoryFactoryBean.afterPropertiesSet();
            JobRepository jobRepository = jobRepositoryFactoryBean.getObject();
            assert jobRepository != null;
            simpleJobLauncher.setJobRepository(jobRepository);
            simpleJobLauncher.afterPropertiesSet();
        }catch (Exception e){
           e.printStackTrace();
        }
        return simpleJobLauncher;
    }
}
